package cn.tedu.weibo.controller;

import cn.tedu.weibo.mapper.UserMapper;
import cn.tedu.weibo.pojo.dto.UserLoginDto;
import cn.tedu.weibo.pojo.dto.UserRegDto;
import cn.tedu.weibo.pojo.entity.User;
import cn.tedu.weibo.pojo.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@RestController
public class UserController {
    @Autowired
    UserMapper userMapper;

    @RequestMapping("/reg")
    public int reg(@RequestBody UserRegDto userRegDto) {
        UserVO u = userMapper.selectByUsername(userRegDto.getUsername());
        if (u != null) {
            return 2;//用户已存在
        }
        User user = new User();
        //把dto里面的数据装进user
        BeanUtils.copyProperties(userRegDto, user);
        userMapper.insert(user);
        return 1;//注册成功
    }
//会话对象存在服务器内存中,重启后消失
    @RequestMapping("/login")
    public int login(@RequestBody UserLoginDto userLoginDto, HttpSession session) {
        UserVO user = userMapper.selectByUsername(userLoginDto.getUsername());
        if (user == null) {
            return 2;//用户不存在
        }
        if (user.getPassword().equals(userLoginDto.getPassword())) {
            session.setAttribute("user", user);
            return 1;//注册成功
        }
        return 3;//密码错误
    }

    @RequestMapping("/currentUser")
    public UserVO currentUser(HttpSession session) {
        //从session中找存进去的UserVO
        return (UserVO) session.getAttribute("user");
    }

    @RequestMapping("/logout")
    public void logout(HttpSession session) {
        //删除会话中的user
        session.removeAttribute("user");
    }

}
